const bodyParser = require('body-parser')
// 引入插件 帮助我们生成token
const JWT = require('jsonwebtoken')
const userList = [{
	username: '张三',
	password: '123'
}, {
	username: '李四',
	password: '666'
}, {
	username: '1911a',
	password: '38'
}]
const Mock = require('mockjs')

const data = Mock.mock({
	'list|20-50': [{
		url: '@image(100x80, @color, img)',
		title: '@ctitle',
		desc: '@cword(10, 20)',
		id: '@id'
	}]
})

module.exports = {
	devServer: {
		before(app) {
			app.use(bodyParser.json());
			// 列表访问接口
			app.get('/api/list', (req, res) => {
				res.send({
					code: 200,
					data: data.list
				})
			})


			// 登录接口
			app.post('/api/login', (req, res) => {
				const {
					username,
					password
				} = req.body
				const item = userList.find(v => v.username === username && v.password === password)

				if (item) {
					res.send({
						code: 200,
						data: {
							// 生成token
							// 语法 JWT.sign(数据, 秘钥)
							token: JWT.sign(item.username, 'qqwwewefw'),
							username: item.username
						},
						message: '登录成功!!'
					})
				} else {
					res.send({
						code: 403,
						data: null,
						message: '账户密码错误， 请重新输入'
					})
				}

			})


			// 注册接口
			app.post('/api/regist', (req, res) => {
				const {
					username,
					password
				} = req.body

				const item = userList.find(v => v.username === username)
				// 用户存在 不可以注册
				if (item) {
					res.send({
						code: 403,
						message: '注册失败， 账户已经存在!!'
					})
				} else {
					// 不存在 允许注册
					userList.push({ username, password })
					res.send({
						code: 200,
						message: '注册成功！！！'
					})
				}

			})
		}
	}
}